MOOC Introduction to Open Data Science 2019: Homework1

The purpose of learning this course is that I would like to learn data analysis skill for the future career. Plus, this online course looks awesome!

MOOC Introduction to Open Data Science 2019: Homework2

Regression and model validation

Describe the work you have done this week and summarize your learning.

  • Describe your work and results clearly.
  • Assume the reader has an introductory course level understanding of writing and reading R code as well as statistical methods.
  • Assume the reader has no previous knowledge of your data or the more advanced methods you are using.

Part1. Know the dataset

Read the students2014 data

students2014 <- read.table(“http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/learning2014.txt”, sep=“,”, header=TRUE)

Explore the data structure and dimensions

str(students2014)

Brief description to original dataset

The resource data is collected from the student self evaluation survey from course Introduction to Social Statistics, fall 2014 - in Finnish. This survey is devided into A, B, C and D parts. - Measures A and C are based on parts A and C in ASSIST (Approaches and Study Skills Inventory for Students). - Measures B (ASSIST B) are connected to the corresponding dimensions (Deep/SUrface/STrategic). - Measure D is based on SATS (Survey of Attitudes Toward Statistics). - Compared to the original 52 item ASSIST we here used a brief version (created by Primi, Chiesi et al), including 32 items.

Brief description to student2014 dataset

The student2014 dataset has 7 variables, including gender, age, attitute, deep, str, surf, and points, and 166 rows. - gender: F (Female, 1), M (Male, 2) - age: age in years - attitude: Measure on the Likert scale (1-5) - deep: Measures B for deep questions - stra: Measures B for surface questions - surf: Measures B for strategic questions - points: Exam points excepted zero

Part2. Graphical overview

Create an plot matrix with ggpairs()

ggpairs(learning2014, lower = list(combo = wrap(“facethist”, bins = 20)))

Create a regression model with multiple explanatory variables

Choose three variables as explanatory variables and fit a regression model

my_model2 <- lm(points ~ attitude + stra + surf, data = learning2014)

  • hint: When there are more than one explanatory variables in the linear model, it is called multiple regression. In R, it is easy to include more than one explanatory variables in your linear model. This is done by simply defining more explanatory variables with the formula argument of lm(), as y ~ x1 + x2 + ..

Brief description to student2014 dataset graphical overview

According to the plot, we can see the correlation and distribution between each variables. For example, the top three variables relative data between points are attitude, stra and surf as 0.437, 0.146 and 0.144.

  • hint: You can use par(mfrow = c(2,2)) to build a graph with 2x2 matrix

Draw diagnostic plots using the plot() function. Choose the plots 1, 2 and 5

plot(my_model2, which = c(1,2,5), caption = list(“Residuals vs Fitted”, “Normal Q-Q”,“Residuals vs Leverage”))

my_model2 diagnostic plots

my_model2 diagnostic plots

  • hint: The numbers in “which = c(number1,number2,number3…)” represent different diagnostic plots, such as 1 for Residuals vs Fitted, 2 for Normal Q-Q and 5 for Residuals vs Leverage.

Explain the assumptions of the model and interpret the validity of those assumptions based on the diagnostic plots

  1. Residuals vs Fitted: This plot shows if residuals have non-linear patterns. In the my_model2 diagnostic plots above, it shows the linear pattern in this data.
  1. Normal Q-Q: This plot shows if residuals are normally distributed. In the my_model2 diagnostic plots above, it shows the data is normally distributed.
  1. Residuals vs Leverage: This plot helps us to find influential cases.When cases are outside of the Cook’s distance (meaning they have high Cook’s distance scores), the cases are influential to the regression results. In the my_model2 diagnostic plots above, it seems no influential outliers.

MOOC Introduction to Open Data Science 2019: Homework3

Step1. Check the data

Read the joined student alcohol consumption data as alc dataset

alc <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/alc.txt", sep=",", header=TRUE)

Summary the alc dataset

str(alc)
## 'data.frame':    382 obs. of  35 variables:
##  $ school    : Factor w/ 2 levels "GP","MS": 1 1 1 1 1 1 1 1 1 1 ...
##  $ sex       : Factor w/ 2 levels "F","M": 1 1 1 1 1 2 2 1 2 2 ...
##  $ age       : int  18 17 15 15 16 16 16 17 15 15 ...
##  $ address   : Factor w/ 2 levels "R","U": 2 2 2 2 2 2 2 2 2 2 ...
##  $ famsize   : Factor w/ 2 levels "GT3","LE3": 1 1 2 1 1 2 2 1 2 1 ...
##  $ Pstatus   : Factor w/ 2 levels "A","T": 1 2 2 2 2 2 2 1 1 2 ...
##  $ Medu      : int  4 1 1 4 3 4 2 4 3 3 ...
##  $ Fedu      : int  4 1 1 2 3 3 2 4 2 4 ...
##  $ Mjob      : Factor w/ 5 levels "at_home","health",..: 1 1 1 2 3 4 3 3 4 3 ...
##  $ Fjob      : Factor w/ 5 levels "at_home","health",..: 5 3 3 4 3 3 3 5 3 3 ...
##  $ reason    : Factor w/ 4 levels "course","home",..: 1 1 3 2 2 4 2 2 2 2 ...
##  $ nursery   : Factor w/ 2 levels "no","yes": 2 1 2 2 2 2 2 2 2 2 ...
##  $ internet  : Factor w/ 2 levels "no","yes": 1 2 2 2 1 2 2 1 2 2 ...
##  $ guardian  : Factor w/ 3 levels "father","mother",..: 2 1 2 2 1 2 2 2 2 2 ...
##  $ traveltime: int  2 1 1 1 1 1 1 2 1 1 ...
##  $ studytime : int  2 2 2 3 2 2 2 2 2 2 ...
##  $ failures  : int  0 0 3 0 0 0 0 0 0 0 ...
##  $ schoolsup : Factor w/ 2 levels "no","yes": 2 1 2 1 1 1 1 2 1 1 ...
##  $ famsup    : Factor w/ 2 levels "no","yes": 1 2 1 2 2 2 1 2 2 2 ...
##  $ paid      : Factor w/ 2 levels "no","yes": 1 1 2 2 2 2 1 1 2 2 ...
##  $ activities: Factor w/ 2 levels "no","yes": 1 1 1 2 1 2 1 1 1 2 ...
##  $ higher    : Factor w/ 2 levels "no","yes": 2 2 2 2 2 2 2 2 2 2 ...
##  $ romantic  : Factor w/ 2 levels "no","yes": 1 1 1 2 1 1 1 1 1 1 ...
##  $ famrel    : int  4 5 4 3 4 5 4 4 4 5 ...
##  $ freetime  : int  3 3 3 2 3 4 4 1 2 5 ...
##  $ goout     : int  4 3 2 2 2 2 4 4 2 1 ...
##  $ Dalc      : int  1 1 2 1 1 1 1 1 1 1 ...
##  $ Walc      : int  1 1 3 1 2 2 1 1 1 1 ...
##  $ health    : int  3 3 3 5 5 5 3 1 1 5 ...
##  $ absences  : int  6 4 10 2 4 10 0 6 0 0 ...
##  $ G1        : int  5 5 7 15 6 15 12 6 16 14 ...
##  $ G2        : int  6 5 8 14 10 15 12 5 18 15 ...
##  $ G3        : int  6 6 10 15 10 15 11 6 19 15 ...
##  $ alc_use   : num  1 1 2.5 1 1.5 1.5 1 1 1 1 ...
##  $ high_use  : logi  FALSE FALSE TRUE FALSE FALSE FALSE ...

The dataset alc includes 35 varibles with 382 rows. The alc_use is the average of column Dalc and Walc (weekday and weekend alcohol consumption). If the average alcohol consumption is higher than 2, it is regarded as high alcohol usage student which is shown in column ‘high_use’ as TRUE.

Choose four interesting variables in alc dataset

Personally, I think alcohol consumption is related to a person’s relationship with family members, higher alcohol concumption may caused by bad relationship, so I select #24 famrel as one onf the analysis target. In addition, in my opinion, if a student tends to have a promising future, he/she may focus on study more rather than be absent in class too often, so I select #14 studytime and #30 absences as the interesing variables. Last, I am interested in if the score is related to alcohol consumption, so I choose #32 G3 as the fourth variable.

  • #14 studytime - weekly study time (numeric: 1 - <2 hours, 2 - 2 to 5 hours, 3 - 5 to 10 hours, or 4 - >10 hours)
  • #24 famrel - quality of family relationships (numeric: from 1 - very bad to 5 - excellent)
  • #30 absences - number of school absences (numeric: from 0 to 93)
  • #32 G3 - final grade (numeric: from 0 to 20, output target)
library(magrittr) # needs to be run every time you start R and want to use %>%
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
alc_4 <- alc %>% select(16, 24, 30, 33, 34, 35)
head(alc_4, n=10)
##    studytime famrel absences G3 alc_use high_use
## 1          2      4        6  6     1.0    FALSE
## 2          2      5        4  6     1.0    FALSE
## 3          2      4       10 10     2.5     TRUE
## 4          3      3        2 15     1.0    FALSE
## 5          2      4        4 10     1.5    FALSE
## 6          2      5       10 15     1.5    FALSE
## 7          2      4        0 11     1.0    FALSE
## 8          2      4        6  6     1.0    FALSE
## 9          2      4        0 19     1.0    FALSE
## 10         2      5        0 15     1.0    FALSE

Graphically explore: a) cross-tabulations b) scatter plots

a) cross-tabulations

high_use vs studytime

alc_4.v1 <- table(alc$high_use, alc$studytime)
round(prop.table(alc_4.v1,1), 2)
##        
##            1    2    3    4
##   FALSE 0.22 0.49 0.20 0.09
##   TRUE  0.38 0.51 0.07 0.04

high_use vs famrel

alc_4.v2 <- table(alc$high_use, alc$famrel)
round(prop.table(alc_4.v2,1), 2)
##        
##            1    2    3    4    5
##   FALSE 0.03 0.03 0.15 0.49 0.31
##   TRUE  0.02 0.08 0.23 0.46 0.21

high_use vs absences

alc_4.v3 <- table(alc$high_use, alc$absences)
round(prop.table(alc_4.v3,1), 2)
##        
##            0    1    2    3    4    5    6    7    8    9   10   11   12   13
##   FALSE 0.35 0.01 0.20 0.01 0.13 0.01 0.07 0.02 0.05 0.01 0.04 0.00 0.02 0.00
##   TRUE  0.20 0.01 0.12 0.04 0.13 0.00 0.10 0.02 0.07 0.00 0.04 0.01 0.04 0.03
##        
##           14   15   16   17   18   19   20   21   22   23   24   25   26   28
##   FALSE 0.03 0.00 0.01 0.00 0.01 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
##   TRUE  0.04 0.02 0.04 0.01 0.02 0.01 0.01 0.00 0.03 0.00 0.01 0.00 0.00 0.01
##        
##           30   54   56   75
##   FALSE 0.00 0.00 0.00 0.00
##   TRUE  0.01 0.01 0.01 0.00

high_use vs G3

alc_4.v4 <- table(alc$high_use, alc$G3)
round(prop.table(alc_4.v4,1), 2)
##        
##            0    4    5    6    7    8    9   10   11   12   13   14   15   16
##   FALSE 0.12 0.00 0.01 0.05 0.02 0.06 0.07 0.13 0.11 0.07 0.05 0.09 0.10 0.05
##   TRUE  0.05 0.01 0.04 0.02 0.02 0.14 0.08 0.20 0.11 0.10 0.11 0.03 0.04 0.04
##        
##           17   18   19   20
##   FALSE 0.01 0.04 0.02 0.00
##   TRUE  0.02 0.02 0.00 0.00
b) scatter plots
## Loading required package: ggplot2
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
## 
## Attaching package: 'GGally'
## The following object is masked from 'package:dplyr':
## 
##     nasa


MOOC Introduction to Open Data Science 2019: Homework4

Step1. Check the Boston dataset

View the dataset
library(dplyr)
library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
head(Boston, n=15)
##       crim   zn indus chas   nox    rm   age    dis rad tax ptratio  black
## 1  0.00632 18.0  2.31    0 0.538 6.575  65.2 4.0900   1 296    15.3 396.90
## 2  0.02731  0.0  7.07    0 0.469 6.421  78.9 4.9671   2 242    17.8 396.90
## 3  0.02729  0.0  7.07    0 0.469 7.185  61.1 4.9671   2 242    17.8 392.83
## 4  0.03237  0.0  2.18    0 0.458 6.998  45.8 6.0622   3 222    18.7 394.63
## 5  0.06905  0.0  2.18    0 0.458 7.147  54.2 6.0622   3 222    18.7 396.90
## 6  0.02985  0.0  2.18    0 0.458 6.430  58.7 6.0622   3 222    18.7 394.12
## 7  0.08829 12.5  7.87    0 0.524 6.012  66.6 5.5605   5 311    15.2 395.60
## 8  0.14455 12.5  7.87    0 0.524 6.172  96.1 5.9505   5 311    15.2 396.90
## 9  0.21124 12.5  7.87    0 0.524 5.631 100.0 6.0821   5 311    15.2 386.63
## 10 0.17004 12.5  7.87    0 0.524 6.004  85.9 6.5921   5 311    15.2 386.71
## 11 0.22489 12.5  7.87    0 0.524 6.377  94.3 6.3467   5 311    15.2 392.52
## 12 0.11747 12.5  7.87    0 0.524 6.009  82.9 6.2267   5 311    15.2 396.90
## 13 0.09378 12.5  7.87    0 0.524 5.889  39.0 5.4509   5 311    15.2 390.50
## 14 0.62976  0.0  8.14    0 0.538 5.949  61.8 4.7075   4 307    21.0 396.90
## 15 0.63796  0.0  8.14    0 0.538 6.096  84.5 4.4619   4 307    21.0 380.02
##    lstat medv
## 1   4.98 24.0
## 2   9.14 21.6
## 3   4.03 34.7
## 4   2.94 33.4
## 5   5.33 36.2
## 6   5.21 28.7
## 7  12.43 22.9
## 8  19.15 27.1
## 9  29.93 16.5
## 10 17.10 18.9
## 11 20.45 15.0
## 12 13.27 18.9
## 13 15.71 21.7
## 14  8.26 20.4
## 15 10.26 18.2
View the dataset structure
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...

The Boston dataset is aiming to see the housing values in suburbs of Boston which includes 14 variables and 506 rows and it contains the following columns:

  • crim: per capita crime rate by town.
  • zn: proportion of residential land zoned for lots over 25,000 sq.ft.
  • indus: proportion of non-retail business acres per town.
  • chas: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise).
  • nox: nitrogen oxides concentration (parts per 10 million).
  • rm: average number of rooms per dwelling.
  • age: proportion of owner-occupied units built prior to 1940.
  • dis: weighted mean of distances to five Boston employment centres.
  • rad: index of accessibility to radial highways.
  • tax: full-value property-tax rate per $10,000.
  • ptratio: pupil-teacher ratio by town.
  • black: 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town.
  • lstat: lower status of the population (percent).
  • medv: median value of owner-occupied homes in $1000s.
Graphical overview

Check the correlations between variables via correlation matrix plot.

## corrplot 0.84 loaded

If the relationship between two variables are more related, the circle would be more bigger and darker. According to the size and color of the circles, we can observe that those variables are related as following:

  • crim: rad, tax
  • zn: dis, age, indus
  • indus: nox, dis, tax
  • chas: N/A
  • nox: age, dis, tax
  • rm: latat, medv
  • age: dis, lstat
  • dis: rad, tax, lstat
  • rad: tax
  • tax: lstat
  • ptratio: medv
  • black: crim, rad, tax…
  • lstat: rm, age…
  • medv: rm

Summary Boston dataset

##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
Standardize the dataset
##         crim         zn      indus       chas        nox        rm        age
## 1 -0.4193669  0.2845483 -1.2866362 -0.2723291 -0.1440749 0.4132629 -0.1198948
## 2 -0.4169267 -0.4872402 -0.5927944 -0.2723291 -0.7395304 0.1940824  0.3668034
## 3 -0.4169290 -0.4872402 -0.5927944 -0.2723291 -0.7395304 1.2814456 -0.2655490
## 4 -0.4163384 -0.4872402 -1.3055857 -0.2723291 -0.8344581 1.0152978 -0.8090878
## 5 -0.4120741 -0.4872402 -1.3055857 -0.2723291 -0.8344581 1.2273620 -0.5106743
## 6 -0.4166314 -0.4872402 -1.3055857 -0.2723291 -0.8344581 0.2068916 -0.3508100
##        dis        rad        tax    ptratio     black      lstat       medv
## 1 0.140075 -0.9818712 -0.6659492 -1.4575580 0.4406159 -1.0744990  0.1595278
## 2 0.556609 -0.8670245 -0.9863534 -0.3027945 0.4406159 -0.4919525 -0.1014239
## 3 0.556609 -0.8670245 -0.9863534 -0.3027945 0.3960351 -1.2075324  1.3229375
## 4 1.076671 -0.7521778 -1.1050216  0.1129203 0.4157514 -1.3601708  1.1815886
## 5 1.076671 -0.7521778 -1.1050216  0.1129203 0.4406159 -1.0254866  1.4860323
## 6 1.076671 -0.7521778 -1.1050216  0.1129203 0.4101651 -1.0422909  0.6705582
##       crim                 zn               indus              chas        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-0.2723  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.2723  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.2723  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.:-0.2723  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 3.6648  
##       nox                rm               age               dis         
##  Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658  
##  1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049  
##  Median :-0.1441   Median :-0.1084   Median : 0.3171   Median :-0.2790  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617  
##  Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566  
##       rad               tax             ptratio            black        
##  Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047   Min.   :-3.9033  
##  1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876   1st Qu.: 0.2049  
##  Median :-0.5225   Median :-0.4642   Median : 0.2746   Median : 0.3808  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058   3rd Qu.: 0.4332  
##  Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372   Max.   : 0.4406  
##      lstat              medv        
##  Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 3.5453   Max.   : 2.9865
Create a categorical variable of the crime rate in the Boston dataset (from the scaled crime rate)

p.s. Use the quantiles as the break points in the categorical variable

# class of the boston_scaled object
class(Boston_scale)
## [1] "matrix"
Boston_scale <- as.data.frame(Boston_scale)

# create a quantile vector of crim and print it
bins <- quantile(Boston_scale$crim)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
# create a categorical variable 'crime'
crime <- cut(Boston_scale$crim, breaks = bins, include.lowest = TRUE)
table(crime)
## crime
## [-0.419,-0.411]  (-0.411,-0.39] (-0.39,0.00739]  (0.00739,9.92] 
##             127             126             126             127
# remove original crim from the dataset
Boston_scale <- dplyr::select(Boston_scale, -crim)

# add the new categorical value to scaled data
Boston_scale <- data.frame(Boston_scale, crime)
Divide the dataset to train and test sets, so that 80% of the data belongs to the train set
# number of rows in the Boston dataset 
n <- nrow(Boston_scale)

# choose randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)

# create train set
train <- Boston_scale[ind,]

# create test set 
test <- Boston_scale[-ind,]

# save the correct classes from test data
correct_classes <- Boston_scale[-ind,]$crime

# remove the crime variable from test data
test <- dplyr::select(test, -crime)
Fit the linear discriminant analysis on the train set
  • Use the categorical crime rate as the target variable and all the other variables in the dataset as predictor variables. Draw the LDA (bi)plot.
  • Save the crime categories from the test set and then remove the categorical crime variable from the test dataset
# linear discriminant analysis
lda.fit <- lda(crime~., data = train)

# print the lda.fit object
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
## [-0.419,-0.411]  (-0.411,-0.39] (-0.39,0.00739]  (0.00739,9.92] 
##       0.2425743       0.2599010       0.2599010       0.2376238 
## 
## Group means:
##                         zn      indus         chas        nox         rm
## [-0.419,-0.411]  0.9419248 -0.8892925 -0.071456607 -0.8695320  0.4050574
## (-0.411,-0.39]  -0.1050211 -0.2451377 -0.009855719 -0.5658743 -0.1865760
## (-0.39,0.00739] -0.3802515  0.1207744  0.252617630  0.4034648  0.1397956
## (0.00739,9.92]  -0.4872402  1.0149946 -0.067271764  1.0782989 -0.4609685
##                        age        dis        rad        tax     ptratio
## [-0.419,-0.411] -0.8504496  0.8226093 -0.6947544 -0.7572511 -0.43806679
## (-0.411,-0.39]  -0.3807528  0.3469944 -0.5509226 -0.4815614 -0.08679874
## (-0.39,0.00739]  0.4048664 -0.3700757 -0.3813870 -0.3184773 -0.29971513
## (0.00739,9.92]   0.8217138 -0.8406937  1.6596029  1.5294129  0.80577843
##                      black       lstat        medv
## [-0.419,-0.411]  0.3854895 -0.75807657  0.49170866
## (-0.411,-0.39]   0.3180304 -0.08396996 -0.03546112
## (-0.39,0.00739]  0.0977499 -0.05056156  0.19121478
## (0.00739,9.92]  -0.6863095  0.95669707 -0.73251025
## 
## Coefficients of linear discriminants:
##                  LD1         LD2         LD3
## zn       0.124419123  0.85798761 -1.01902672
## indus    0.009767002 -0.09514844  0.41180582
## chas    -0.077929244 -0.06340750  0.03124155
## nox      0.273502106 -0.75146023 -1.23159752
## rm      -0.104859230 -0.09585069 -0.09284860
## age      0.366490404 -0.32771724 -0.37982933
## dis     -0.065870509 -0.30465922  0.21255111
## rad      3.225125995  0.93681851 -0.26162684
## tax     -0.020289543 -0.16785218  0.65693402
## ptratio  0.118372961  0.09499694 -0.32092102
## black   -0.146158690 -0.01385488  0.08578102
## lstat    0.139435406 -0.17056246  0.60288582
## medv     0.126987812 -0.39618835 -0.07510328
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9442 0.0386 0.0173
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(train$crime)

# plot the lda results
plot(lda.fit, dimen = 2)
lda.arrows(lda.fit, myscale = 1)

Predict the classes with the LDA model on the test data. Cross tabulate the results with the crime categories from the test set. Comment on the results.
# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)

# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
##                  predicted
## correct           [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
##   [-0.419,-0.411]              16             11               2              0
##   (-0.411,-0.39]                3             10               8              0
##   (-0.39,0.00739]               0              6              15              0
##   (0.00739,9.92]                0              0               1             30
Reload the Boston dataset and standardize the dataset
  • Calculate the distances between the observations. Run k-means algorithm on the dataset. Investigate what is the optimal number of clusters and run the algorithm again.
  • Visualize the clusters. For example with the pairs() or ggpairs() functions, where the clusters are separated with colors and interpret the results
library(MASS)
data('Boston')

# scale the dataset
bs <- scale(Boston)
bs <- as.data.frame(bs)

# distance measure 1: euclidean distance matrix
dist_eu <- dist(bs, method = "euclidean")

# look at the summary of the distances
summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970
# distance measure 2: manhattan distance matrix
dist_man <- dist(bs, method = "manhattan")

# look at the summary of the distances
summary(dist_man)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.2662  8.4832 12.6090 13.5488 17.7568 48.8618
# k-means clustering
# plot the Boston dataset with clusters
km <-kmeans(bs, centers = 4)
pairs(bs[6:10], col = km$cluster)

# k-means clustering
km <-kmeans(bs, centers = 3)
pairs(bs[6:10], col = km$cluster)

# k-means clustering
km <-kmeans(bs, centers = 2)
pairs(bs[6:10], col = km$cluster)

# k-means clustering
km <-kmeans(bs, centers = 1)
pairs(bs[6:10], col = km$cluster)

As shown in the k-means graph above (from center=4 to 1), the pair graph with center=2 seems the most resonable seperation. In the graph when center=3, some cluster are ambiguous winthin one group.

Bonus
  • Perform k-means on the original Boston data with some reasonable number of clusters (> 2).
  • Perform LDA using the clusters as target classes. Include all the variables in the Boston data in the LDA model.
Boston_scale_original <- scale(Boston)
Boston_scale_original <- as.data.frame(Boston_scale_original)

# k-means clustering
km_original <-kmeans(Boston_scale_original, centers = 4)
pairs(Boston_scale_original[6:10], col = km_original$cluster)

# k-means clustering
km_original <-kmeans(Boston_scale_original, centers = 3)
pairs(Boston_scale_original[6:10], col = km_original$cluster)

Visualize the results with a biplot (include arrows representing the relationships of the original variables to the LDA solution).

Interpret the results. Which variables are the most influencial linear separators for the clusters? (0-2 points to compensate any loss of points from the above exercises)

Super-Bonus

Run the code below for the (scaled) train data that you used to fit the LDA. The code creates a matrix product, which is a projection of the data points.


MOOC Introduction to Open Data Science 2019: Homework5

1. Graphical Overview and Summaries

(0-3 points) Describe and interpret the outputs, commenting on the distributions of the variables and the relationships between them.

human_ <- read.csv(file = "data/human.csv", sep = ",", header = TRUE)

# Access GGally
library(GGally)

# visualize the 'human_' variables
ggpairs(human_,
        title="human data", # title of the plot
        colour = "sex") # aesthetics, ggplot2 style
## Warning in warn_if_args_exist(list(...)): Extra arguments: 'colour' are being
## ignored. If these are meant to be aesthetics, submit them using the 'mapping'
## variable within ggpairs with ggplot2::aes or ggplot2::aes_string.

# compute the correlation matrix and visualize it with corrplot
cor(human_)
##                Edu2.FM      Labo.FM   Life.Exp     Edu.Exp         GNI
## Edu2.FM    1.000000000  0.009564039  0.5760299  0.59325156  0.43030485
## Labo.FM    0.009564039  1.000000000 -0.1400125  0.04732183 -0.02173971
## Life.Exp   0.576029853 -0.140012504  1.0000000  0.78943917  0.62666411
## Edu.Exp    0.593251562  0.047321827  0.7894392  1.00000000  0.62433940
## GNI        0.430304846 -0.021739705  0.6266641  0.62433940  1.00000000
## Mat.Mor   -0.660931770  0.240461075 -0.8571684 -0.73570257 -0.49516234
## Ado.Birth -0.529418415  0.120158862 -0.7291774 -0.70356489 -0.55656208
## Parli.F    0.078635285  0.250232608  0.1700863  0.20608156  0.08920818
##              Mat.Mor  Ado.Birth     Parli.F
## Edu2.FM   -0.6609318 -0.5294184  0.07863528
## Labo.FM    0.2404611  0.1201589  0.25023261
## Life.Exp  -0.8571684 -0.7291774  0.17008631
## Edu.Exp   -0.7357026 -0.7035649  0.20608156
## GNI       -0.4951623 -0.5565621  0.08920818
## Mat.Mor    1.0000000  0.7586615 -0.08944000
## Ado.Birth  0.7586615  1.0000000 -0.07087810
## Parli.F   -0.0894400 -0.0708781  1.00000000

This Human dataset contains the information about Human Development Index (HDI) which includes Edu2.FM (Female education index), Labo.FM (Female labour market index), Life.Exp (Life expectancy index), Edu.Exp (Education epectancy index), GNI (Gross national income), Mat.Mor (Maternal mortality ratio), Ado.Birth (Adolescent birth rate) and Parli.F (Female shares of parliamentary seats) as the dataset variables.

HDI has three dimentions, including Long and healthy life, Knowledge and A decent standard of living which are able to be evaluated by life expentanct index, education index and GNI index.

According to the human data distribution plot, we can see the correlation between Life.Exp, Edu.Exp and GNI are highly related (> 0.6)

2. Principal Component Analysis (PCA)

(0-2 points) - Perform PCA on the not standardized human data. Show the variability captured by the principal components. - Draw a biplot displaying the observations by the first two principal components (PC1 coordinate in x-axis, PC2 coordinate in y-axis), along with arrows representing the original variables.

# perform principal component analysis on the not standardized human data
pca_human <- prcomp(human_)
pca_human
## Standard deviations (1, .., p=8):
## [1] 1.854416e+04 1.855219e+02 2.518701e+01 1.145441e+01 3.766241e+00
## [6] 1.565912e+00 1.912052e-01 1.591112e-01
## 
## Rotation (n x k) = (8 x 8):
##                     PC1           PC2           PC3           PC4           PC5
## Edu2.FM   -5.607472e-06  0.0006713951 -3.412027e-05 -2.736326e-04 -0.0022935252
## Labo.FM    2.331945e-07 -0.0002819357  5.302884e-04 -4.692578e-03  0.0022190154
## Life.Exp  -2.815823e-04  0.0283150248  1.294971e-02 -6.752684e-02  0.9865644425
## Edu.Exp   -9.562910e-05  0.0075529759  1.427664e-02 -3.313505e-02  0.1431180282
## GNI       -9.999832e-01 -0.0057723054 -5.156742e-04  4.932889e-05 -0.0001135863
## Mat.Mor    5.655734e-03 -0.9916320120  1.260302e-01 -6.100534e-03  0.0266373214
## Ado.Birth  1.233961e-03 -0.1255502723 -9.918113e-01  5.301595e-03  0.0188618600
## Parli.F   -5.526460e-05  0.0032317269 -7.398331e-03 -9.971232e-01 -0.0716401914
##                     PC6           PC7           PC8
## Edu2.FM    2.180183e-02  6.998623e-01  7.139410e-01
## Labo.FM    3.264423e-02  7.132267e-01 -7.001533e-01
## Life.Exp  -1.453515e-01  5.380452e-03  2.281723e-03
## Edu.Exp    9.882477e-01 -3.826887e-02  7.776451e-03
## GNI       -2.711698e-05 -8.075191e-07 -1.176762e-06
## Mat.Mor    1.695203e-03  1.355518e-04  8.371934e-04
## Ado.Birth  1.273198e-02 -8.641234e-05 -1.707885e-04
## Parli.F   -2.309896e-02 -2.642548e-03  2.680113e-03
# draw a biplot of the principal component representation and the original variables
biplot(pca_human, choices = 1:2)
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

> According to the biplot, the GNI tends to PC2 dimension and others variables tend to PC1 dimension.

3. Comparison between standardized and non-standardized dataset

(0-4 points) - Standardize the variables in the human data and repeat the above analysis. Interpret the results of both analysis (with and without standardizing). - Are the results different? Why or why not? Include captions (brief descriptions) in your plots where you describe the results by using not just your variable names, but the actual phenomenons they relate to.

# standardize the variables
human_std <- scale(human_)
# print out summaries of the standardized variables
summary(human_std)
##     Edu2.FM           Labo.FM           Life.Exp          Edu.Exp       
##  Min.   :-2.8189   Min.   :-2.6247   Min.   :-2.7188   Min.   :-2.7378  
##  1st Qu.:-0.5233   1st Qu.:-0.5484   1st Qu.:-0.6425   1st Qu.:-0.6782  
##  Median : 0.3503   Median : 0.2316   Median : 0.3056   Median : 0.1140  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.5958   3rd Qu.: 0.7350   3rd Qu.: 0.6717   3rd Qu.: 0.7126  
##  Max.   : 2.6646   Max.   : 1.6632   Max.   : 1.4218   Max.   : 2.4730  
##       GNI             Mat.Mor          Ado.Birth          Parli.F       
##  Min.   :-0.9193   Min.   :-0.6992   Min.   :-1.1325   Min.   :-1.8203  
##  1st Qu.:-0.7243   1st Qu.:-0.6496   1st Qu.:-0.8394   1st Qu.:-0.7409  
##  Median :-0.3013   Median :-0.4726   Median :-0.3298   Median :-0.1403  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.3712   3rd Qu.: 0.1932   3rd Qu.: 0.6030   3rd Qu.: 0.6127  
##  Max.   : 5.6890   Max.   : 4.4899   Max.   : 3.8344   Max.   : 3.1850
# perform principal component analysis (with the SVD method)
pca_human_std <- prcomp(human_std)
# draw a biplot of the principal component representation and the original variables
biplot(pca_human_std, choices = 1:2)

> According to the biplot with standardized data, the Edu2.FM (Female education index), Life.Exp (Life expectancy index), Edu.Exp (Education epectancy index) and GNI (Gross national income) are related and tend to PC2 dimension. Comparing to the non-standardized data, the biplot with standardized data is more clearer to interpret the correlation between the several variables.

4. Personal interpretations of the first two principal component dimensions

(0-2 points) Give your personal interpretations of the first two principal component dimensions based on the biplot drawn after PCA on the standardized human data.

# create and print out a summary of pca_human
s <- summary(pca_human)


# rounded percetanges of variance captured by each PC
pca_pr <- round(1*s$importance[2, ], digits = 5)

# print out the percentages of variance


# create object pc_lab to be used as axis labels
paste0(names(pca_pr), " (", pca_pr, "%)")
## [1] "PC1 (0.9999%)" "PC2 (1e-04%)"  "PC3 (0%)"      "PC4 (0%)"     
## [5] "PC5 (0%)"      "PC6 (0%)"      "PC7 (0%)"      "PC8 (0%)"
# draw a biplot
biplot(pca_human, cex = c(0.8, 1), col = c("grey40", "deeppink2"), xlab = NA, ylab = NA)
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length =
## arrow.len): zero-length arrow is of indeterminate angle and so skipped

5. Multiple Correspondence Analysis

(0-4 points) Load the tea dataset from the package Factominer. Explore the data briefly: look at the structure and the dimensions of the data and visualize it. Then do Multiple Correspondence Analysis on the tea data (or to a certain columns of the data, it’s up to you). Interpret the results of the MCA and draw at least the variable biplot of the analysis. You can also explore other plotting options for MCA. Comment on the output of the plots.